//
//  WeChatLoginViewController.m
//  MeterMart
//
//  Created by ENERGY on 2018/10/8.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "RegisterViewController.h"
static int countTime = 599;
@interface RegisterViewController ()<UITextFieldDelegate>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)UIView * headerView;
@property (nonatomic, strong)UITextField * phoneNumTextField;//电话号
@property (nonatomic, strong)UITextField * verificationCodeTextField;//验证码
@property (nonatomic, strong)UIButton * verificationCodeBtn;//验证码按钮
@property (nonatomic, strong)UIButton * registerBtn;//绑定按钮
@property (nonatomic, strong)UITextField * passwordTextField;//密码
@property (nonatomic, strong)UITextField * repasswordTextField;//确认密码
@property (nonatomic, strong)NSTimer * timer;
@property (nonatomic, strong)NSString * phoneString;
@property (nonatomic, strong)NSString * verificationString;
@property (nonatomic, strong) UIActivityIndicatorView * activityIndicator;//菊花
- (void)test:(NSTimer *)timer;
@end

@implementation RegisterViewController(networking)
- (void)sendVerificationCode{
    NSDictionary * dic = @{
                           @"phone":self.phoneNumTextField.text,
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"usiosApi/sendnum" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            self.verificationCodeBtn.enabled = NO;
            //初始化定时器
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(test:) userInfo:nil repeats:YES];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}
//注册接口
- (void)registerData{
    NSDictionary * dic = @{
                           @"phone":self.phoneNumTextField.text,
                           @"code":self.self.verificationCodeTextField.text,
                           @"password":self.passwordTextField.text,
                           @"repassword":self.repasswordTextField.text
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"usiosApi/register" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        ShowMessage(@"注册成功");
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            int64_t delayInSeconds = 1;// 延迟的时间
            /*
             *@parameter 1,时间参照，从此刻开始计时
             *@parameter 2,延时多久，此处为秒级，还有纳秒等。10ull * NSEC_PER_MSEC
             */
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [self hiddenProgressHUD];
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }else{
            [self hiddenProgressHUD];
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}
@end
@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"注册";
    
    [self.view addSubview:self.tableView];
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVI_HEIGHT) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.tableHeaderView = self.headerView;
    }return _tableView;
}
- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVI_HEIGHT)];
        //标题
        UIImageView * titleLab = [[UIImageView alloc] initWithFrame:CGRectMake(0, 30/WIDTH_6_SCALE, 60/WIDTH_6_SCALE, 60/WIDTH_6_SCALE)];
        titleLab.image = [UIImage imageNamed:@"appSelf"];
        titleLab.layer.cornerRadius = 30/WIDTH_6_SCALE;
        titleLab.layer.masksToBounds = YES;
        titleLab.centerX = SCREEN_WIDTH/2;
        [_headerView addSubview:titleLab];
        //手机号
        self.phoneNumTextField = [[UITextField alloc] initWithFrame:CGRectMake(40/WIDTH_6_SCALE, 43/WIDTH_6_SCALE + titleLab.bottom, SCREEN_WIDTH - 80/WIDTH_6_SCALE, 40/WIDTH_6_SCALE)];
        self.phoneNumTextField.delegate = self;
        self.phoneNumTextField.placeholder = @"请输入手机号";
        self.phoneNumTextField.font = DEF_FontSize_14;
        self.phoneNumTextField.leftViewMode = UITextFieldViewModeAlways;
        UIView * phoneNumPlaceHoldImgBG = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 39/WIDTH_6_SCALE, self.phoneNumTextField.height)];
        phoneNumPlaceHoldImgBG.backgroundColor = [UIColor clearColor];
        UIImageView *phoneNumImageView = [[UIImageView alloc] initWithFrame:CGRectMake(15/WIDTH_6_SCALE, 13/WIDTH_6_SCALE, 11/WIDTH_6_SCALE, 16/WIDTH_6_SCALE)];
        phoneNumImageView.image = [UIImage imageNamed:@"boundPhone"];
        [phoneNumPlaceHoldImgBG addSubview:phoneNumImageView];
        self.phoneNumTextField.leftView = phoneNumPlaceHoldImgBG;
        self.phoneNumTextField.backgroundColor = getColor(mainColor);
        [_headerView addSubview:self.phoneNumTextField];
        //验证码
        self.verificationCodeTextField = [[UITextField alloc] initWithFrame:CGRectMake(self.phoneNumTextField.left, self.phoneNumTextField.bottom + 16/WIDTH_6_SCALE, 191/WIDTH_6_SCALE, self.phoneNumTextField.height)];
        self.verificationCodeTextField.delegate = self;
        self.verificationCodeTextField.placeholder = @"请输入验证码";
        self.verificationCodeTextField.font = DEF_FontSize_14;
        self.verificationCodeTextField.backgroundColor = getColor(mainColor);
        self.verificationCodeTextField.leftViewMode = UITextFieldViewModeAlways;
        UIView * verificationCodePlaceHoldImgBG = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 39/WIDTH_6_SCALE, self.verificationCodeTextField.height)];
        verificationCodePlaceHoldImgBG.backgroundColor = [UIColor clearColor];
        UIImageView *verificationCodeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(15/WIDTH_6_SCALE, 13/WIDTH_6_SCALE, 14/WIDTH_6_SCALE, 16/WIDTH_6_SCALE)];
        verificationCodeImageView.image = [UIImage imageNamed:@"lock"];
        [verificationCodePlaceHoldImgBG addSubview:verificationCodeImageView];
        self.verificationCodeTextField.leftView = verificationCodePlaceHoldImgBG;
        self.verificationCodeTextField.backgroundColor = getColor(mainColor);
        [_headerView addSubview:self.verificationCodeTextField];
        //验证码按钮
        self.verificationCodeBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.verificationCodeTextField.right + 10/WIDTH_6_SCALE, self.verificationCodeTextField.top, SCREEN_WIDTH - self.verificationCodeTextField.left * 2 - 10/WIDTH_6_SCALE - self.verificationCodeTextField.width, self.verificationCodeTextField.height)];
        [self.verificationCodeBtn setBackgroundColor:getColor(mainRedColor)];
        self.verificationCodeBtn.titleLabel.font = DEF_FontSize_14;
        [self.verificationCodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.verificationCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                [self.verificationCodeBtn addTarget:self action:@selector(verificationCodeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_headerView addSubview:self.verificationCodeBtn];
        //密码
        self.passwordTextField = [[UITextField alloc] initWithFrame:CGRectMake(self.phoneNumTextField.left, self.verificationCodeTextField.bottom + 16/WIDTH_6_SCALE, self.phoneNumTextField.width, self.phoneNumTextField.height)];
        self.passwordTextField.delegate = self;
        self.passwordTextField.placeholder = @"请输入密码";
        self.passwordTextField.secureTextEntry = YES;
        self.passwordTextField.font = DEF_FontSize_14;
        self.passwordTextField.backgroundColor = getColor(mainColor);
        self.passwordTextField.leftViewMode = UITextFieldViewModeAlways;
        UIView * passwordPlaceHoldImgBG = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 39/WIDTH_6_SCALE, self.verificationCodeTextField.height)];
        passwordPlaceHoldImgBG.backgroundColor = [UIColor clearColor];
        UIImageView * passwordImageView = [[UIImageView alloc] initWithFrame:CGRectMake(15/WIDTH_6_SCALE, 13/WIDTH_6_SCALE, 14/WIDTH_6_SCALE, 16/WIDTH_6_SCALE)];
        passwordImageView.image = [UIImage imageNamed:@"lock"];
        [passwordPlaceHoldImgBG addSubview:passwordImageView];
        self.passwordTextField.leftView = passwordPlaceHoldImgBG;
        self.passwordTextField.backgroundColor = getColor(mainColor);
        [_headerView addSubview:self.passwordTextField];
        //确认密码
        self.repasswordTextField = [[UITextField alloc] initWithFrame:CGRectMake(self.phoneNumTextField.left, self.passwordTextField.bottom + 16/WIDTH_6_SCALE, self.phoneNumTextField.width, self.phoneNumTextField.height)];
        self.repasswordTextField.delegate = self;
        self.repasswordTextField.placeholder = @"请再次输入密码";
        self.repasswordTextField.secureTextEntry = YES;
        self.repasswordTextField.font = DEF_FontSize_14;
        self.repasswordTextField.backgroundColor = getColor(mainColor);
        self.repasswordTextField.leftViewMode = UITextFieldViewModeAlways;
        UIView * repasswordPlaceHoldImgBG = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 39/WIDTH_6_SCALE, self.verificationCodeTextField.height)];
        passwordPlaceHoldImgBG.backgroundColor = [UIColor clearColor];
        UIImageView * repasswordImageView = [[UIImageView alloc] initWithFrame:CGRectMake(15/WIDTH_6_SCALE, 13/WIDTH_6_SCALE, 14/WIDTH_6_SCALE, 16/WIDTH_6_SCALE)];
        repasswordImageView.image = [UIImage imageNamed:@"lock"];
        [repasswordPlaceHoldImgBG addSubview:repasswordImageView];
        self.repasswordTextField.leftView = repasswordPlaceHoldImgBG;
        self.repasswordTextField.backgroundColor = getColor(mainColor);
        [_headerView addSubview:self.repasswordTextField];
        //注册按钮
        self.registerBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.phoneNumTextField.left, self.repasswordTextField.bottom + 20/WIDTH_6_SCALE, self.phoneNumTextField.width, 40/WIDTH_6_SCALE)];
        [self.registerBtn setBackgroundColor:getColor(mainColor)];
        [self.registerBtn setTitle:@"注册" forState:UIControlStateNormal];
        self.registerBtn.titleLabel.font = DEF_FontSize_14;
        [self.registerBtn setTitleColor:getColor(@"898989") forState:UIControlStateNormal];
        [self.registerBtn addTarget:self action:@selector(registerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_headerView addSubview:self.registerBtn];
        _headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.registerBtn.bottom + 20/WIDTH_6_SCALE);
    }return _headerView;
}
#pragma mark - action
- (void)verificationCodeBtnClick:(UIButton *)sender{
    if (self.phoneNumTextField.text.length == 0 || [self.phoneNumTextField.text isEqualToString:@""] || self.phoneNumTextField.text == nil) {
        [self.view makeToast:@"请输入手机号" duration:1 position:CSToastPositionCenter];
        return;
    }
    if ([self valiMobile:self.phoneNumTextField.text]) {
        [self.view endEditing:YES];
        [self sendVerificationCode];
    }else{
        [self.view makeToast:@"请输入正确的手机号" duration:1 position:CSToastPositionCenter];
    }
}
- (void)registerBtnClick:(UIButton *)sender{
    NSLog(@"注册");
//    if (self.phoneNumTextField.text.length == 0 || [self.phoneNumTextField.text isEqualToString:@""] || self.phoneNumTextField.text == nil) {
//        [self.view makeToast:@"请输入手机号" duration:1 position:CSToastPositionCenter];
//        return;
//    }
//    if ([self valiMobile:self.phoneNumTextField.text]) {
//        if (self.verificationCodeTextField.text.length == 0 || [self.verificationCodeTextField.text isEqualToString:@""] || self.verificationCodeTextField.text == nil) {
//            [self.view makeToast:@"请输入验证码" duration:1 position:CSToastPositionCenter];
//        }else{
            [self registerData];
//        }
//    }else{
//        [self.view makeToast:@"请输入正确的手机号" duration:1 position:CSToastPositionCenter];
//    }
}
- (void)test:(NSTimer *)timer{
    if (countTime != 1) {
        countTime -= 1;
        self.verificationCodeBtn.enabled = NO;
        [self.verificationCodeBtn setTitle:[NSString stringWithFormat:@"剩余%i秒", countTime] forState:UIControlStateNormal];
    } else {
        self.verificationCodeBtn.enabled = YES;
        [self.verificationCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        countTime = 30;
        //停掉定时器
        [self.timer invalidate];
        self.timer = nil;
    }
}
#pragma mark - textFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == self.phoneNumTextField) {
        self.phoneString = string;
    }
    if (textField == self.verificationCodeTextField) {
        self.verificationString = string;
    }
    if (self.phoneString.length && self.verificationString.length > 0) {
        [self.registerBtn setBackgroundColor:getColor(mainRedColor)];
        [self.registerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.registerBtn.userInteractionEnabled = YES;
    }else{
        [self.registerBtn setBackgroundColor:getColor(mainColor)];
        [self.registerBtn setTitleColor:getColor(@"898989") forState:UIControlStateNormal];
        self.registerBtn.userInteractionEnabled = NO;
    }
    return YES;
}

//判断手机号码格式是否正确
- (BOOL)valiMobile:(NSString *)mobile{
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11){
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}
@end
